package com.haople.sso.client.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;

import com.haople.sso.client.SsoClient;
import com.haople.sso.client.service.TicketValidateService;
import com.haople.sso.client.service.impl.TicketValidateServiceImpl;
import com.haople.sso.core.service.CookieService;
import com.haople.sso.core.service.impl.CookieServiceImpl;
import com.haople.sso.core.vo.Ticket;

/**
 * sso过滤器
 * @author Administrator
 *
 */
public class ClientFilter implements Filter,SsoClient {

	private static final TicketValidateService ticketValidateService=new TicketValidateServiceImpl();
	private static final CookieService cookieService=new CookieServiceImpl();
	
	public void init(FilterConfig filterConfig) throws ServletException {
		String ssoService=filterConfig.getInitParameter("ssoService"); //从配置文件中获取sso服务的地址
		String cookieSecret=filterConfig.getInitParameter("cookieSecret"); //从配置文件中获取cookie秘钥
		ticketValidateService.setSsoService(ssoService);
		cookieService.setCookieSecret(cookieSecret);
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) servletRequest;
		HttpServletResponse response=(HttpServletResponse) servletResponse;
		HttpSession	httpSession=request.getSession();
		String userId=request.getParameter("userkey");
		String ticketValue=request.getParameter("ticket");
		//从cookie中获取票据信息（userId，ticket）
		if(StringUtils.isEmpty(ticketValue) || StringUtils.isEmpty(userId)){
			Ticket ticket=cookieService.getTicket(request.getCookies());
			if(ticket!=null){
				userId=ticket.getUserId();
				ticketValue=ticket.getTicket();
			}
		}
		if(StringUtils.isEmpty(ticketValue) || StringUtils.isEmpty(userId)){ //如果值依然为空
			String service=request.getRequestURL().toString();
			String loginUrl=ticketValidateService.getLoginUrl();
			response.sendRedirect(loginUrl+"?service="+service);
			return;
		}
		final String currentTicket=userId+"|"+ticketValue;
		String sessionTicket=null;
		if(!StringUtils.isEmpty(httpSession.getAttribute(SSO_CLIENT_SESSION))){
			sessionTicket=String.valueOf(httpSession.getAttribute(SSO_CLIENT_SESSION));
		}
		if(sessionTicket==null || (sessionTicket!=null && !sessionTicket.equals(currentTicket))) {
			//验证票据有效性
			boolean flag=ticketValidateService.ticketValidate(userId, ticketValue);
			if(!flag){ //如果验证时失败
				String service=request.getRequestURL().toString();
				String loginUrl=ticketValidateService.getLoginUrl();
				response.sendRedirect(loginUrl+"?service="+service);
				return;
			}else{
				httpSession.setAttribute(SSO_CLIENT_SESSION, currentTicket);
			}
		}
		chain.doFilter(request, response); //放过执行
	}
	
	public void destroy() {
		
	}

}
